package com.university.trade.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class ResponseUtil {
	/**
	 * 输出字符串
	 * @param response
	 * @param o
	 * @throws Exception
	 */
	public static void write(HttpServletResponse response, Object o) throws Exception {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.println(o.toString());
		out.flush();
		out.close();
	}
	/**
	 * 输出json数据
	 * @param json
	 * @param response
	 * @throws IOException
	 */
	public static void printJson(Object obj, HttpServletResponse response) throws IOException {
		response.setContentType("application/json;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(objectToJsonString(obj));
		out.flush();
		out.close();
	}
	/**
	 * 输出text数据
	 * @param text
	 * @param response
	 * @throws IOException
	 */
	public static void printText(String text, HttpServletResponse response) throws IOException {
		response.setContentType("text/plain;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(text);
		out.flush();
		out.close();
	}
	/**
	 * 把object转换成为json string
	 * @param obj
	 * @return
	 */
	public static String objectToJsonString(Object obj){
		if(null == obj){
			return "";
		}else if(obj instanceof java.util.Map){
			return JSONObject.fromObject(obj).toString();
		}else if(obj instanceof java.util.List){
			return JSONArray.fromObject(obj).toString();
		}else {
			return JSONObject.fromObject(obj).toString();
		}
	}
	/**
	 * 把object转换成为json string
	 * @param digits 需要几位随机数
	 * @return
	 */
	public static String randomNum(int digits){
		StringBuffer sb = new StringBuffer();
		Random random = new Random();
		for(int i = 0; i < digits ; i++){
			sb.append(random.nextInt(10));
		}
		return sb.toString();
	}
}
